<template>
  <el-dialog
    title="评阅作业"
    :visible.sync="dialogVisible"
    width="650px"
    top="0"
    :before-close="cancelBtn"
    :close-on-click-modal="false"
    @open="open"
  >
    <el-form
      v-loading="loading"
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-position="top"
      class="readForm"
    >
      <div class="cont_title">
        <div class="line"></div>
        <div class="lf">
          <span>
            {{stuWork.jiguanProvince}}{{stuWork.jiguanProvince==stuWork.jiguanCity?"":stuWork.jiguanCity}}{{stuWork.school}}</span>
          <span>{{stuWork.name}}</span>
          <span>提交的作业</span>
        </div>
        <div class="rt" v-if="type==1">编号: {{stuInfo.workNum}}</div>
      </div>
      <div class="cont_title_2">文字描述</div>
      <div class="cont_info">{{stuWork.stuAnswer}}</div>
      <div class="cont_title_2">相关附件</div>
      <div class="upload_box">
        <div v-if="stuFileList.length>0" class="img_list" v-for="(item, index) in stuFileList" :key="index">
          <div>
            <el-image :src="fileImg"></el-image>
            <div class="item_name">{{item.name}}</div>
            <div class="item_remove" @click="downloadStuFile(item.url)">下载</div>
          </div>
        </div>
        <div v-if="stuFileList.length<=0" class="img_list">
          <div>
            <div class="item_name">暂无相关附件</div>
          </div>
        </div>

        <div style="clear: both;"></div>
      </div>
      <div class="cont_title">
        <div class="line"></div>
        评阅结果
      </div>
      <el-form-item label="导师评分" prop="score">
        <el-input
          v-model="formData.score"
          size="small"
          placeholder="请评分(输入0-100之内的整数)"
          @input="inputValue"
        />
      </el-form-item>
      <el-form-item label="导师评语" prop="teaCommment">
        <el-input
          type="textarea"
          v-model="formData.teaCommment"
          placeholder="请输入300字以内的评语"
          size="small"
          :maxlength="300"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="相关附件" prop="teacherUrl">
        <div class="fj_info">1、请上传1-10份相关附件;</div>
        <div class="fj_info">2、单个附件大小不超过100M,支持JPG、JPEG、PNG、docx、doc、pdf、mp4等格式;</div>

        <div class="upload_box">
          <div class="img_list" v-for="(item, index) in teaFileList" :key="index">
            <div>
              <el-image :src="fileImg"></el-image>
              <div class="item_name">{{item.name}}</div>
              <div class="item_remove" @click="handleRemove(item)">删除</div>
            </div>
          </div>

          <el-upload
            v-if="teaFileList.length<10"
            ref="systemLogo"
            name="multipartFile"
            :action="imgAction"
            :headers="headers"
            :file-list="teaFileList"
            :disabled="upLoading"
            list-type="picture-card"
            :show-file-list="false"
            :before-upload="beforeUpload"
            :on-progress="handleProgress"
            :on-success="handleSuccess">
            <i v-if="!upLoading" class="el-icon-plus"></i>
            <i v-if="upLoading" class="el-icon-loading"></i>
          </el-upload>
        </div>
      </el-form-item>
      <el-form-item class="btn">
        <el-button type="primary" @click="confirm">保存</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
  import {getToken, getCampJobId} from "@/utils/auth";
  import {GetStuWork, SaveTheRead, GetAllReadInfo, SaveYiRead} from "@/api/campSystem/campOper";
  import fileImg from "@/assets/images/file_img.png";

  export default {
    name: "ReadForm",
    props: {
      dialogVisibleFu: Boolean,
      campIdFu: [Number, String],
      stuInfoFu: [Object, String],
      typeFu: [Number, String]
    },
    data() {
      return {
        fileImg: fileImg,
        loading: false,
        dialogVisible: this.dialogVisibleFu,
        type: this.typeFu,// 来源（1-未评阅 2-已评阅）
        campId: this.campIdFu,// 营地id
        stuInfo: this.stuInfoFu,// 学生-信息
        jobId: null,// 作业id
        stuWork: {},// 学生-作业
        stuFileList: [],// 学生-相关附件
        teaFileList: [],// 老师-相关附件
        formData: {
          campId: null,
          campWorkTid: null,
          uuid: null,
          score: null,
          teaCommment: null,
          teacherUrl: null
        },// 老师-评阅结果
        rules: {
          score: [
            {required: true, message: '请评分(输入0-100之内的整数)', trigger: 'blur'}
          ],
        },
        upLoading: false,// 老师-上传loading
        // 上传图片请求头
        headers: {
          Authorization: "Bearer " + getToken()
        },
        imgAction: process.env.VUE_APP_BASE_API + "/modules-campsite/ld/UploadWorkForStudent",
      };
    },
    methods: {
      open() {
        this.jobId = getCampJobId();
        if (this.type == 1) {
          this.getStuWork();
        } else if (this.type == 2) {
          this.getYiStuWork();
        }
      },
      // 保存按钮
      confirm() {
        this.$refs['formRef'].validate((valid) => {
          if (!valid) return
          if(this.type==1){
            this.notReadHandle();
          }else if(this.type==2){
            this.yiReadHandle();
          }
        })
      },
      // 下载学生附件
      downloadStuFile(url) {
        let reg = /^.+(\.pdf|\.txt|\.mp3|\.mp4)$/
        if(reg.test(url)){
          window.open(url, '_black');
        }else{
          window.open(url, '_self');
        }
      },
      // 导师评分0-100限制
      inputValue(value) {
        if (value.length > 1 && value.slice(0, 1) == 0) {
          return this.formData.score = 0;
        } else if (value.length >= 3 && value > 100) {
          return this.formData.score = 100;
        }
        this.formData.score = value.replace(/[^\d]/g, '');
      },
      // 已评阅-获取学生答案
      getYiStuWork() {
        GetAllReadInfo({
          campId: this.campId,
          campWorkTid: this.jobId,
          uuid: this.stuInfo.uuid
        })
          .then(response => {
            console.log(response);
            if (response.code != 200) {
              return this.msgError(response.msg);
            }
            this.stuWork = response.data;
            this.formData.score =  this.stuWork['score'];
            this.formData.teaCommment =  this.stuWork['teacherCommment'];
            this.formData.teacherUrl =  this.stuWork['teacherUrl'];

            let url = this.stuWork.stuEnclosureUrl;
            if (this.stuWork.stuEnclosureUrl) {
              let arr = url.split(',');
              arr.forEach(item => {
                this.stuFileList.push({
                  url: item,
                  name: item.split('/work/')[1],
                  status: 'success'
                })
              })
            } else {
              this.stuFileList = [];
            }
            let urlT = this.stuWork.teacherUrl;
            if (this.stuWork.teacherUrl) {
              let arr = urlT.split(',');
              arr.forEach(item => {
                this.teaFileList.push({
                  url: item,
                  name: item.split('workforstudent/')[1],
                  status: 'success'
                })
              })
            } else {
              this.teaFileList = [];
            }
          })
          .catch(error => {
            console.log(error);
          });
      },
      // 已评阅-评阅
      yiReadHandle(){
        this.formData.campId = this.campId;
        this.formData.campWorkTid = this.jobId;
        this.formData.uuid = this.stuInfo.uuid;
        SaveYiRead(this.formData)
          .then(response => {
            console.log(response);
            if (response.code != 200) {
              return this.msgError(response.msg);
            }
            this.msgSuccess(response.msg);
            this.cancelBtnTrue();
          })
          .catch(error => {
            console.log(error);
          });
      },
      // 未评阅-获取学生答案
      getStuWork() {
        GetStuWork({
          campId: this.campId,
          campWorkTid: this.jobId,
          uuid: this.stuInfo.uuid
        })
          .then(response => {
            console.log(response);
            if (response.code != 200) {
              return this.msgError(response.msg);
            }
            this.stuWork = response.data;
            let url = this.stuWork.stuEnclosureUrl;
            if (this.stuWork.stuEnclosureUrl) {
              let arr = url.split(',');
              arr.forEach(item => {
                this.stuFileList.push({
                  url: item,
                  name: item.split('/work/')[1],
                  status: 'success'
                })
              })
            } else {
              this.stuFileList = [];
            }
          })
          .catch(error => {
            console.log(error);
          });
      },
      // 未评阅-评阅
      notReadHandle(){
        this.formData.campId = this.campId;
        this.formData.campWorkTid = this.jobId;
        this.formData.uuid = this.stuInfo.uuid;
        SaveTheRead(this.formData)
          .then(response => {
            console.log(response);
            if (response.code != 200) {
              return this.msgError(response.msg);
            }
            this.msgSuccess(response.msg);
            this.cancelBtnTrue();
          })
          .catch(error => {
            console.log(error);
          });
      },
      // 成功确认取消,关闭弹框，修改父组件的值
      cancelBtnTrue() {
        this.stuWork = {};
        this.stuFileList = [];
        this.teaFileList = [];
        this.$refs['formRef'].resetFields();
        this.dialogVisible = false;
        this.$emit("closeDialog", this.dialogVisible, true);
      },
      // 取消,关闭弹框，修改父组件的值
      cancelBtn() {
        this.stuWork = {};
        this.stuFileList = [];
        this.teaFileList = [];
        this.dialogVisible = false;
        this.$emit("closeDialog", this.dialogVisible, false);
      },
      // 删除文件
      handleRemove(data) {
        this.teaFileList = this.teaFileList.filter(item => {
          return item != data;
        })
        this.formData.teacherUrl = this.teaFileList.map(item => {
          return item.url
        }).join(',');
        console.log(this.teaFileList)
        console.log(this.formData.teacherUrl)
      },
      // 文件上传成功时的钩子
      handleSuccess(res, file, fileList) {
        if (res.code != 200) {
          this.upLoading = false;
          return this.msgError(res.msg);
        }
        let length = this.teaFileList.length;
        this.teaFileList[length] = {
          status: 'success',
          name: res.msg.split('workforstudent/')[1],
          url: res.msg
        }
        this.formData.teacherUrl = this.teaFileList.map(item => {
          return item.url
        }).join(',');
        this.upLoading = false;
        this.msgSuccess('上传成功');
      },
      handleProgress(event, file, fileList) {
        this.upLoading = true;
      },
      // 上传文件之前的钩子
      beforeUpload(file) {
        const isLt10M = file.size / 1024 / 1024 <= 100;

        if (!isLt10M) {
          this.$message.error('上传的附件大小不能超过 100M!');
          return false;
        }
        return isLt10M;
      },
    },
    watch: {
      dialogVisibleFu() {
        this.dialogVisible = this.dialogVisibleFu;
      },
      campIdFu() {
        this.campId = this.campIdFu;
      },
      stuInfoFu() {
        this.stuInfo = this.stuInfoFu;
      },
      typeFu() {
        this.type = this.typeFuFu;
      }
    },
  };
</script>

<style scoped lang="scss">
  ::v-deep .el-dialog {
    max-height: 90%;
    display: flex;
    flex-flow: column;

    .el-dialog__header {
      text-align: center;
      padding: 20px;
    }

    .el-dialog__body {
      padding: 0 50px 30px;
      flex: 1;
      overflow-y: scroll;
      display: flex;
      flex-flow: column;

      .lf {
        float: left;
      }

      .rt {
        float: right;
      }

      .readForm {
        flex: 1;

        .cont_title {
          position: relative;
          height: 38px;
          line-height: 38px;
          font-size: 16px;
          font-family: PingFang SC;
          font-weight: 500;
          color: #12141C;
          padding-left: 10px;
          margin-top: 10px;

          span {
            margin-right: 15px;
          }

          .line {
            position: absolute;
            left: 0;
            top: 50%;
            transform: translateY(-50%);
            width: 3px;
            height: 14px;
            background-color: #12141C;
            opacity: 0.4;
          }
        }

        .cont_title_2 {
          height: 28px;
          line-height: 28px;
          font-size: 14px;
          font-family: PingFang SC;
          font-weight: 500;
          color: #12141C;
          padding: 0 10px;
        }

        .cont_info {
          line-height: 20px;
          font-size: 12px;
          font-family: PingFang SC;
          font-weight: 500;
          color: #999999;
          padding: 0 10px 10px 10px;
        }

        .fj_info {
          line-height: 24px;
          font-size: 12px;
          font-family: PingFang SC;
          font-weight: 500;
          color: #999999;
        }

        .el-form-item {
          margin-bottom: 15px;
          padding: 0 10px;

          .el-form-item__label {
            height: 32px;
            line-height: 32px;
            font-size: 12px;
            font-family: PingFang SC;
            font-weight: 500;
            color: #12141C;
          }

          .el-form-item__content {
            .el-input,
            .el-input-number {
              width: 100%;
              height: 36px;

              .el-input__inner {
                text-align: left;
                height: 36px;
                border-radius: 4px;
                border: 1px solid #E1E3E6;
                background-color: #FFFFFF;
                color: #656872;

                &:hover {
                  border-color: #4D75F3;
                }

                &:focus {
                  border-color: #4D75F3;
                }
              }
            }

            .el-textarea__inner {
              min-height: 100px !important;
            }
          }

          &.btn {
            margin-top: 50px;

            .el-form-item__content {
              text-align: center;
            }
          }
        }

        .upload_box {
          .img_list {
            position: relative;
            float: left;
            width: 160px;
            height: 120px;
            text-align: center;
            background: transparent;
            border-radius: 4px;
            border: 2px dashed #E1E3E6;
            margin: 0 8px 8px 0;
            padding: 5px;
            display: flex;
            flex-flow: column;
            justify-content: center;
            align-items: center;

            > div {
              width: 100%;

              .el-image {
                width: 30px;
                height: 30px;
                min-height: 30px;
                display: block;
                margin: 0 auto;
                border: 0;

                img {
                  width: auto;
                  height: auto;
                  max-width: 100% !important;
                  max-height: 100% !important;
                }
              }

              .item_name {
                font-size: 12px;
                color: #999999;
                line-height: 16px;
                word-wrap: break-word;
                margin: 5px 0 10px;
              }

              .item_remove {
                width: 40px;
                font-size: 12px;
                color: #999999;
                font-weight: bold;
                line-height: 16px;
                margin: 0 auto;

                &:hover {
                  cursor: pointer;
                  color: red;
                }
              }
            }
          }

          .el-upload {
            width: 160px !important;
            height: 120px !important;
            line-height: 120px !important;
            background: transparent;
            border-radius: 4px;
            border: 2px dashed #E1E3E6;
            text-align: center !important;
          }
        }
      }
    }
  }
</style>






